<template>
  <div class="app-container">
    <div style="flex: 1;min-width: 290px;">
      <div style="margin-bottom: 4px;">
        <el-button type="primary" size="mini" @click="handleAdd(null)">新增</el-button>
      </div>
      <el-tree
        ref="tree"
        :data="treeList"
        show-checkbox
        node-key="id"
        default-expand-all
        @node-click="nodeClick"
        @check="checkChange">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        【{{data.articleTypeCode}}】
        <span class="custom-tree-span">{{ data.articleTypeName }}</span>
        <span style="float: right; padding-right: 10px;">
          <el-button
            type="text"
            size="mini"
            @click="() => handleEdit('articleType', 0, data)">
            编辑
          </el-button>
        </span>
      </span>
      </el-tree>
    </div>

    <div style="flex: 4;margin-left: 10px;">
      <div style="margin-bottom: 4px;">
        <el-button type="primary" size="mini" @click="handleAdd('articleInfo')">新增</el-button>
        <!--<el-button type="danger" size="mini" @click="handleDeleteAll()">删除</el-button>-->
      </div>
      <el-table ref="multipleTable" :data="infoList" v-loading="listLoading" element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column label="文章名称">
          <template slot-scope="scope">
            {{scope.row.articleName}}
          </template>
        </el-table-column>
        <el-table-column label="文章介绍">
          <template slot-scope="scope">
            <span>{{scope.row.articleIntro}}</span>
          </template>
        </el-table-column>
        <el-table-column label="文章来源">
          <template slot-scope="scope">
            <span>{{scope.row.articleFrom}}</span>
          </template>
        </el-table-column>
        <el-table-column label="作者">
          <template slot-scope="scope">
            <span>{{scope.row.author}}</span>
          </template>
        </el-table-column>
        <el-table-column label="排序">
          <template slot-scope="scope">
            <span>{{scope.row.sort}}</span>
          </template>
        </el-table-column>
        <el-table-column label="阅读数">
          <template slot-scope="scope">
            <span>{{scope.row.counts}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.articleStatus==0">草稿</span>
            <span v-else-if="scope.row.articleStatus==1">已发布</span>
            <span v-else-if="scope.row.articleStatus==2">已下架</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit('articleInfo', scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">下架</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 4px;">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :page-size="pageSize"
          :current-page="pageNum"
          :total="pageTotal"
          @current-change="pageChange">
        </el-pagination>
      </div>
    </div>
    <!--类型编辑-->
    <el-dialog :title="dialogFormTitle" :show-close="false" :close-on-press-escape="false"
               :close-on-click-modal="false" :visible.sync="typeVisible">
      <el-form :model="form">
        <el-form-item label="编号" :label-width="formLabelWidth">
          <el-input v-model="form.articleTypeCode" :disabled="codeDisabled"></el-input>
        </el-form-item>
        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input v-model="form.articleTypeName"></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.notes"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSubmit('articleType')">取 消</el-button>
        <el-button type="primary" @click="submit('articleType')">确 定</el-button>
      </div>
    </el-dialog>
    <!--内容编辑-->
    <el-dialog :title="dialogFormTitle" :show-close="false" :close-on-press-escape="false"
               :close-on-click-modal="false" :visible.sync="infoVisible">
      <el-form :model="infoForm">
        <el-form-item label="文章类型ID" :label-width="formLabelWidth">
          <el-input :disabled="true" v-model="infoForm.articleTypeId"></el-input>
        </el-form-item>
        <el-form-item label="文章名称" :label-width="formLabelWidth">
          <el-input v-model="infoForm.articleName"></el-input>
        </el-form-item>
        <el-form-item label="文章图片链接" :label-width="formLabelWidth">
          <el-input v-model="infoForm.articleImg"></el-input>
          <input type="file" id="uploadFile" @change="fileUpload"></input>
          <span style="color: red">这里只能上传尺寸100*100的图片</span>
        </el-form-item>
        <el-form-item label="文章介绍" :label-width="formLabelWidth">
          <el-input v-model="infoForm.articleIntro"></el-input>
        </el-form-item>
        <el-form-item label="文章状态" :label-width="formLabelWidth">
         <!-- <el-input v-model="infoForm.adStatus"></el-input>--><!--0：草稿，1：已发布，2：已下架-->
          <el-select v-model="infoForm.articleStatus" placeholder="请选择">
            <el-option label="草稿" value="0" key="0">
              <span style="float: left">草稿</span>
              <span style="float: right; color: #8492a6; font-size: 13px">0</span>
            </el-option>
            <el-option label="已发布" value="1" key="1">
              <span style="float: left">已发布</span>
              <span style="float: right; color: #8492a6; font-size: 13px">1</span>
            </el-option>
            <el-option label="已下架" value="2" key="2">
              <span style="float: left">已下架</span>
              <span style="float: right; color: #8492a6; font-size: 13px">2</span>
            </el-option>
          </el-select>
          <span>广告状态 ---- 0：草稿，1：已发布，2：已下架</span>
        </el-form-item>
        <el-form-item label="文章来源" :label-width="formLabelWidth">
          <el-input v-model="infoForm.articleFrom"></el-input>
        </el-form-item>
        <el-form-item label="文章作者" :label-width="formLabelWidth">
          <el-input v-model="infoForm.author"></el-input>
        </el-form-item>
        <el-form-item label="内容类型" :label-width="formLabelWidth">
          <el-select v-model="infoForm.contentType" placeholder="请选择">
            <el-option label="自身内容" value="1" key="1">
              <span style="float: left">自身内容</span>
              <span style="float: right; color: #8492a6; font-size: 13px">1</span>
            </el-option>
            <el-option label="外部链接内容" value="2" key="2">
              <span style="float: left">外部链接内容</span>
              <span style="float: right; color: #8492a6; font-size: 13px">2</span>
            </el-option>
          </el-select>
          <span>内容类型。1:自身内容，2:外部链接内容</span>
        </el-form-item>
        <el-form-item label="文章内容链接" :label-width="formLabelWidth">
          <el-input v-model="infoForm.contentUrl"></el-input>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth">
          <el-input v-model="infoForm.sort"></el-input>
        </el-form-item>
        <el-form-item label="阅读数" :label-width="formLabelWidth">
          <el-input v-model="infoForm.counts"></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="infoForm.notes"></el-input>
        </el-form-item>
        <el-form-item label="文章内容" :label-width="formLabelWidth">
          <UE :config=UEconfig ref="UE"></UE>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSubmit('articleInfo')">取 消</el-button>
        <el-button type="primary" @click="submit('articleInfo')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<script>
  import { adApi } from '@/api/article'
  import {parseTime} from '@/utils/index'
  import UE from '@/components/UEdieor/ue.vue'

  export default {
    components:{UE},
    data() {
      return {
        pageNum: 1, // 当前页
        pageSize: 20, // 每页数
        pageTotal: 0, // 总页数
        list: null,
        infoList: null,
        listLoading: true,
        typeVisible: false,
        infoVisible:false,
        dialogFormTitle: '',
        formLabelWidth: '100px',
        form: {},
        infoForm:{},
        codeDisabled: false,
        dialogPermissionVisible: false,
        articleTypeId: '',
        articleTypeName: '',
        treeList: null,
        clickTreeBtn: false,
        UEconfig: {//UEdieor编辑器配置
          //可以在此处定义工具栏的内容
          // toolbars: [
          //  ['fullscreen', 'undo', 'redo','|','bold', 'italic', 'underline',
          //  '|','superscript','subscript','|', 'insertorderedlist', 'insertunorderedlist',
          //  '|','fontfamily','fontsize','justifyleft','justifyright','justifycenter','justifyjustify']
          // ],
          autoHeightEnabled: false,
          autoFloatEnabled: true,
          initialContent:'请输入内容',   //初始化编辑器的内容,也可以通过textarea/script给值，看官网例子
          autoClearinitialContent:false, //是否自动清除编辑器初始内容，注意：如果focus属性设置为true,这个也为真，那么编辑器一上来就会触发导致初始化的内容看不到了
          initialFrameWidth: null,
          initialFrameHeight: 450,
          BaseUrl: '',
          UEDITOR_HOME_URL: process.env.UEDITOR_HOME_URL
        }
      }
    },
    filters: {
    },
    created() {
      this.fetchData()
    },
    methods: {
      fetchData() {
        this.form = {};
        adApi.getTypeList(this.pageSize,this.pageSize,{}).then(response => {
          console.log(response);
          this.treeList = response.list;
          if (response.list.length > 0) {
            this.articleTypeId = response.list[0].id;
            this.$refs.tree.setCheckedKeys([this.articleTypeId]);
            this.articleTypeName = response.list[0].articleTypeName;
            this.fetchItem();
          }
        })
      },
      fetchItem() {
        this.listLoading = true;
        adApi.infoList(this.pageNum, this.pageSize, this.articleTypeId, null).then(response => {
          this.list = response.list;
          setTimeout(() => { this.listLoading = false }, 1000);
          this.infoList = response.list;
          this.pageTotal = response.total;
          this.pageNum = response.pageNum;
        })
      },
      /*打开新增窗口*/
      handleAdd(type) {
        if (type === 'articleInfo') {
          this.infoForm = {};
          this.dialogFormTitle = '新增文章内容：' + this.articleTypeName;
          this.infoVisible = true;
          this.infoForm.articleTypeId = this.articleTypeId;
        }else{
          this.dialogFormTitle = '新增文章类型';
          this.typeVisible = true;
          this.codeDisabled = false
        }
      },
      /*打开编辑窗口*/
      handleEdit(type, index, row) {
        console.log('handleEdit');
        if(type == 'articleType'){//广告类型
          this.clickTreeBtn = true;
          this.codeDisabled = true;
          this.form = row;
          this.dialogFormTitle = '类型编辑';
          this.typeVisible = true
        }else if(type == 'articleInfo'){//广告内容
          this.dialogFormTitle = '文章内容编辑 - '+ this.articleTypeName;
          this.infoForm = row;
          this.infoVisible = true;
          this.UEconfig.initialContent = row.content
        }
      },
      handleDelete(index, row) {
        this.$confirm('确认下架', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          row.articleStatus = 2;
          adApi.infoUpdate(row).then(response => {
            this.$message({
              type: 'success',
              message: '下架成功'
            })
            this.fetchItem()
          })
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // })
        })
      },
      /*提交*/
      submit(type) {
        if(type=='articleType'){//广告类型
          console.log(this.form);
          if (this.form.id && this.form.id !== '') {
            // 编辑
            adApi.typeUpdate(this.form).then(response => {
              this.typeVisible = false;
              this.fetchData()
            })
          } else {
            // 新增
            adApi.typeAdd(this.form).then(response => {
              this.typeVisible = false;
              this.fetchData()
            })
          }
        }else if(type=='articleInfo'){//广告详情
          this.infoForm.content = this.$refs.UE.getUEContent();//获取富文本编辑器的内容
          console.log(this.infoForm);
          if (this.infoForm.id && this.infoForm.id !== '') {
            // 编辑
            adApi.infoUpdate(this.infoForm).then(response => {
              this.infoVisible = false;
              this.fetchItem();
            })
          } else {
            // 新增
            adApi.infoAdd(this.infoForm).then(response => {
              this.infoVisible = false;
              this.fetchItem();
            })
          }
        }
      },
      /*取消*/
      cancelSubmit(type) {
        if(type=='articleType'){
          this.typeVisible = false;
          this.fetchData()
        }else if(type=="articleInfo"){
          this.infoVisible = false;
          this.fetchItem();
        }
      },
      //时间格式化
      parseTime(time) {
        if(time != null){
          return parseTime(time, null)
        }
      },
      /*文件上传*/
      fileUpload(e){
        console.log(e);
        // 通过DOM取文件数据
        let file = document.getElementById('uploadFile').files[0];
        let imgSrc = window.URL.createObjectURL(file);
        let img = new Image();
        img.src = imgSrc;
        let that = this;
        img.onload = function () {
          console.log(img.width+"---"+img.height)
          if(img.width != 100 || img.height != 100){
            that.$message({
              type: 'error',
              message: '上传图片的尺寸必须是 100*100'
            });
            return;
          }
          let size = Math.floor(file.size / 1024);//文件大小kb
          if(size > 1024){
            that.$message({
              type: 'error',
              message: '上传文件不能大于1MB'
            });
            return;
          }
          let data = new FormData();
          data.append('uploadFile', file);
          adApi.fileUpload(data).then(response => {
            console.log(response);
            if(response.status == '200'){
              that.infoForm.articleImg = response.data.url;
            }
          })
        }
      },
      pageChange(val) {
        this.pageNum = val;
        this.fetchItem()
      },
      nodeClick(data, node, obj) {
        if (this.clickTreeBtn) {
          this.clickTreeBtn = false;
          return
        }
        // alert(data.dictName)
        // this.$refs.tree.setCheckedKeys([])
        this.$refs.tree.setCheckedKeys([data.id]);
        this.pageNum = 1;
        this.articleTypeId = data.id;
        this.articleTypeName = data.articleTypeName;
        this.fetchItem()
      },
      checkChange(data, checkedData) {
        // tree的复选框实现单选
        this.$refs.tree.setCheckedKeys([data.id]);
        this.pageNum = 1;
        this.articleTypeId = data.id;
        this.adName = data.adName;
        this.fetchItem()
      }
    }
  }
</script>

<style scoped>
  .app-container {
    display: flex;
  }
  .custom-tree-node {
    width: 100%;
  }
  .custom-tree-span {
    height: 28px;
    display: inline-block;
    padding-top: 4px;
  }
</style>
